package com.itheima52.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.db.dao.AddressDao;
import com.itheima52.mobilesafe.utils.ToastUtils;

/**
 * 来电提醒的服务
 * 
 * @author ludaxu
 * 
 */
public class AddressService extends Service {

	private TelephonyManager tm;
	private MyListener listener;
	private OutCallReceiver receiver;
	private WindowManager mWM;
	private View view;
	private SharedPreferences mPref;
	private int startX;
	private int startY;
	private WindowManager.LayoutParams params;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 服务被创建
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mPref = getSharedPreferences("config", MODE_PRIVATE);
		tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		listener = new MyListener();
		tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);// 监听来电的状态

		// 动态的注册广播
		receiver = new OutCallReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
		registerReceiver(receiver, filter);

	}

	class MyListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:// 电话铃声响了
				System.out.println("来电铃响...");
				// 根据来电的号码,查询归属地
				String address = AddressDao.getAddress(incomingNumber);
				// ToastUtils.showToast(AddressService.this, address);
				showToast(address);
				break;
			case TelephonyManager.CALL_STATE_IDLE:// 电话闲置状态
				if (mWM != null && view != null) {
					mWM.removeView(view);// 从window中移除view
				}

			default:
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}

	}

	/**
	 * 服务被销毁
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);// 停止来电监听
		unregisterReceiver(receiver);// 注销广播

	}

	/**
	 * 监听去电的广播接收者 需要权限 :android.permission.PROCESS_OUTGOING_CALLS
	 * 
	 * @author ludaxu
	 * 
	 */
	class OutCallReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String number = getResultData();// 获得去电号码
			String address = AddressDao.getAddress(number);
			// Toast.makeText(context, address, 0).show();
			showToast(address);

		}

	}

	/**
	 * 自定义归属地浮窗
	 */
	private void showToast(String text) {
		mWM = (WindowManager) getSystemService(WINDOW_SERVICE);
		final int winWidth = mWM.getDefaultDisplay().getWidth();// 得到屏幕的宽度
		final int winHeight = mWM.getDefaultDisplay().getHeight();// 得到屏幕的宽高

		params = new WindowManager.LayoutParams();
		params.height = WindowManager.LayoutParams.WRAP_CONTENT;
		params.width = WindowManager.LayoutParams.WRAP_CONTENT;
		params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		params.format = PixelFormat.TRANSLUCENT;
		params.type = WindowManager.LayoutParams.TYPE_PHONE;
		// 将重心位置设置成左上方(0,0),默认的重心位置为中心点
		params.gravity = Gravity.LEFT + Gravity.TOP;
		params.setTitle("toast");
		int lastX = mPref.getInt("lastX", 0);
		int lastY = mPref.getInt("lastY", 0);
		// 设置浮窗的位置,基于左上方的偏移量
		params.x = lastX;
		params.y = lastY;
		// view = new TextView(AddressService.this);
		// view.setText(text);
		// view.setTextColor(Color.RED);
		// 背景图片资源列表
		int[] background = new int[] { R.drawable.call_locate_white,
				R.drawable.call_locate_orange, R.drawable.call_locate_blue,
				R.drawable.call_locate_gray, R.drawable.call_locate_green };
		view = View.inflate(AddressService.this, R.layout.toast_address, null);
		LinearLayout llToastAddress = (LinearLayout) view
				.findViewById(R.id.ll_toast_address);
		int style = mPref.getInt("address_style", 0);// 读取保存的style
		llToastAddress.setBackgroundResource(background[style]);
		TextView tvText = (TextView) view.findViewById(R.id.tv_number);
		tvText.setText(text);
		mWM.addView(view, params);// 将view添加到屏幕上(Window)

		// 需要权限:android.permission.SYSTEM_ALERT_WINDOW
		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:

					startX = (int) event.getRawX();
					startY = (int) event.getRawY();

					break;
				case MotionEvent.ACTION_MOVE:
					int endX = (int) event.getRawX();
					int endY = (int) event.getRawY();
					// 计算偏移量
					int dx = endX - startX;
					int dy = endY - startY;
					// 更新浮窗位置
					params.x += dx;
					params.y += dy;

					// 防止坐标偏离屏幕
					if (params.x < 0) {
						params.x = 0;
					}
					if (params.y < 0) {
						params.y = 0;
					}
					if (params.x > winWidth - view.getWidth()) {
						params.x = winWidth - view.getWidth();
					}
					if (params.y > winHeight - view.getHeight()) {
						params.y = winHeight - view.getHeight();
					}
					mWM.updateViewLayout(view, params);
					startX = (int) event.getRawX();
					startY = (int) event.getRawY();

					break;
				case MotionEvent.ACTION_UP:
					// 记录坐标点
					Editor edit = mPref.edit();
					edit.putInt("lastX", params.x);
					edit.putInt("lastY", params.y);
					edit.commit();
					break;

				default:
					break;
				}
				return true;
			}
		});
	}

}
